//
//  SchoolListViewController.m
//  Hxcsfw
//
//  Created by 企友软mac on 2017/11/24.
//  Copyright © 2017年 企友软mac. All rights reserved.
//

#import "SchoolListViewController.h"
#import "SchoolTeachViewCell.h"
#import "ReportVideoModel.h"
#import "UIImageView+WebCache.h"
#import "VideoDetailViewController.h"
#import "CheckNetwork.h"

@interface SchoolListViewController ()<UITableViewDelegate,UITableViewDataSource>{
    int j;
}

@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *arrData;

@end

@implementation SchoolListViewController

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    if ([WShareUtil sharedData].dicSleSymbol) {

        NSInteger tag = [[WShareUtil sharedData].dicSleSymbol[@"index"] integerValue];

        WLog(@"%@",self.arrData[tag]);

        ReportVideoModel *reporModel = self.arrData[tag];
        if ([[WShareUtil sharedData].dicSleSymbol[@"chosen"] boolValue]) {
            reporModel.chosen = @"1";
        }
        [self.arrData replaceObjectAtIndex:tag withObject:reporModel];

        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:tag inSection:0];
        //2.将indexPath添加到数组
        NSArray <NSIndexPath *> *indexPathArray = @[indexPath];
        //3.传入数组，对当前cell进行刷新
        [self.tableView reloadRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationAutomatic];
        WLog(@"%@",self.arrData[tag]);
        WLog(@"%@",[WShareUtil sharedData].dicSleSymbol);
        [WShareUtil sharedData].dicSleSymbol = nil;
    }

    if ([WShareUtil sharedData].dicBuySymbol) {

        for (int i = 0; i < self.arrData.count; i++) {
            if ([[WShareUtil sharedData].dicBuySymbol[@"id"] isEqualToString:[self.arrData[i] strId]]) {

                ReportVideoModel *reporModel = self.arrData[i];
                if ([[WShareUtil sharedData].dicBuySymbol[@"boughten"] boolValue]) {
                    reporModel.boughten = @"1";
                }

                [self.arrData replaceObjectAtIndex:i withObject:reporModel];

                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                //2.将indexPath添加到数组
                NSArray <NSIndexPath *> *indexPathArray = @[indexPath];
                //3.传入数组，对当前cell进行刷新
                [self.tableView reloadRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationAutomatic];
                [WShareUtil sharedData].dicBuySymbol = nil;
            }
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    j=1;
    self.arrData = [NSMutableArray array];

    [self.view addSubview:self.tableView];
    [self.tableView.superview insertSubview:[UIView new] atIndex:0];
//    [self requestListDataStrNum:@"1" type:_strType isRefrsh:YES];
    [self notifyRequestListData];
    [self.tableView.header beginRefreshing];
}

- (void)noWifiRefershingEnd {
    [self.tableView.header endRefreshing];
    [self.tableView.footer endRefreshing];
    [WShareUtil sharedData].isShowWait = YES;

}

- (void)notifyRequestListData{

    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

        [self requestListDataStrNum:@"1" type:_strType isRefrsh:YES];
        j = 1;
    }];

    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSString *num = [NSString stringWithFormat:@"%d",++j];
        [self requestListDataStrNum:num type:_strType isRefrsh:NO];
    }];
}

- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, WSCREENH_WIDTH, WSCREENH_HEIGHT - 64) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        self.tableView.estimatedRowHeight =0;
        self.tableView.estimatedSectionHeaderHeight =0;
        self.tableView.estimatedSectionFooterHeight =0;        _tableView.showsVerticalScrollIndicator = YES;
        _tableView.bounces = YES;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.arrData count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *identCell = @"HomeListCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identCell];

    if (cell == nil) {
        SchoolTeachViewCell *teachViewCell = [[[NSBundle mainBundle] loadNibNamed:@"SchoolTeachViewCell" owner:self options:nil] lastObject];

        if (self.arrData.count > 0 && self.arrData) {
            
//            [teachViewCell.imgCell sd_setImageWithURL:[NSURL URLWithString:[self.arrData[indexPath.row] imgsrc]] placeholderImage:[UIImage imageNamed:@"school_image.png"]];

            GifView *gifView = [WShareUtil animatedGifWithData:teachViewCell.imgCell];
            [teachViewCell.imgCell addSubview:gifView];

            [teachViewCell.imgCell sd_setImageWithURL:[NSURL URLWithString:[_arrData[indexPath.row] imgsrc]] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                [gifView removeFromSuperview];
            }];

            if ([[_arrData[indexPath.row] chosen] boolValue]) {
                teachViewCell.lbType.hidden = NO;
                teachViewCell.lbType.text = @"已选课";
                teachViewCell.lbType.backgroundColor = WRGBColor(235, 107, 12);
            } else if (![[_arrData[indexPath.row] chosen] boolValue] && [[_arrData[indexPath.row] boughten] boolValue]) {
                teachViewCell.lbType.hidden = NO;
                teachViewCell.lbType.text = @"已购买";
                teachViewCell.lbType.backgroundColor = WRGBColor(208, 45, 39);
            }
            
            teachViewCell.lbNum.text = [NSString stringWithFormat:@"%@人学习过",[self.arrData[indexPath.row] strView]];
            //价格与免费
            if ([[_arrData[indexPath.row] isfree] isEqualToString:@"true"]) {
                teachViewCell.lbPrice.text = @"免费";
                teachViewCell.lbPrice.textColor = [UIColor colorWithRed:0.37 green:0.71 blue:0.11 alpha:1];
                
            }else{
                teachViewCell.lbPrice.text = [NSString stringWithFormat:@"¥%@",[_arrData[indexPath.row] charged]];
            }
            teachViewCell.lbTitle.text = [self.arrData[indexPath.row] strTitle];

            [UILabel changeSpaceForLabel:teachViewCell.lbTitle];
        }
        cell = teachViewCell;
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    CheckNetwork *checkNetwork = [[CheckNetwork alloc] init];
    if (![checkNetwork isNetworkReachable]) {//没网
        return;
    } else {
        VideoDetailViewController *videoDetailVc = [[VideoDetailViewController alloc] init];
        videoDetailVc.strId = [self.arrData[indexPath.row] strId];
        videoDetailVc.intTag = indexPath.row;
        videoDetailVc.symbol = School_L_Symbol;
        [self.navigationController pushViewController:videoDetailVc animated:YES];
    }

}

- (void)requestListDataStrNum:(NSString *)pageNum type:(NSString *)type isRefrsh:(BOOL)isRefrsh{

    [WShareUtil sharedData].isShowWait = NO;

    NSDictionary *parametersDict;
    NSString *nologinuser = [WShareUtil getUUID];
    if (_isInvoiceModelList) {

        if ([WShareUtil sharedData].dicSession) {

            parametersDict = @{@"mode":@"native",@"service":@"train",@"content":@{@"username":[WShareUtil sharedData].dicSession[@"nsrsbh"],@"revert":@"paginate",@"type":@"zzsfp",@"pagesize":@"10",@"pagenumber":pageNum,@"apptype":@"ios"}};

        } else {
            parametersDict = @{@"mode":@"native",@"service":@"train",@"content":@{@"nologinuser":nologinuser,@"revert":@"paginate",@"type":@"zzsfp",@"pagesize":@"10",@"pagenumber":pageNum,@"apptype":@"ios"}};
        }
    } else {

        if ([WShareUtil sharedData].dicSession) {

            parametersDict = @{@"mode":@"native",@"service":@"train",@"content":@{@"username":[WShareUtil sharedData].dicSession[@"nsrsbh"],@"revert":@"paginate",@"type":type,@"pagesize":@"10",@"pagenumber":pageNum,@"apptype":@"ios"}};

        } else {

            parametersDict = @{@"mode":@"native",@"service":@"train",@"content":@{@"nologinuser":nologinuser,@"revert":@"paginate",@"type":type,@"pagesize":@"10",@"pagenumber":pageNum,@"apptype":@"ios"}};
        }
    }
    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};


    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        WLog(@"------%@",responseObject);
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];

        if ([successStr isEqualToString:@"false"]) {
            return;
        }
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];
        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if (isRefrsh) {
            [self.arrData removeAllObjects];
        }

        NSArray *arrData = returnDic[@"data"];

        for (NSDictionary *dic in arrData) {
            ReportVideoModel *videoModel = [ReportVideoModel mj_objectWithKeyValues:dic];
            [self.arrData addObject:videoModel];
        }

        [self.tableView reloadData];
        [self noWifiRefershingEnd];
        
        ///* --- 图片式提醒
        UIView *view = [self.tableView viewWithTag:10000];
        [view removeFromSuperview];
        HHNonePage *_nonePage = [[HHNonePage alloc]init];
        _nonePage = nil;
        if (_arrData.count == 0) {
            _nonePage = [[HHNonePage alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
            _nonePage.tag = 10000;
            [self.tableView addSubview:_nonePage];
        }
        //*/
        
        if (arrData.count < 10) {
            // 拿到当前的上拉刷新控件，变为没有更多数据的状态
            [self.tableView.footer endRefreshingWithNoMoreData];
        }

    } failure:^(NSError *error) {
        WLog(@"失败");
        [self noWifiRefershingEnd];
        ///* --- 图片式提醒
        UIView *view = [self.tableView viewWithTag:10000];
        [view removeFromSuperview];
        HHNonePage *_nonePage = [[HHNonePage alloc]init];
        _nonePage = nil;
        if (_arrData.count == 0) {
            _nonePage = [[HHNonePage alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
            _nonePage.tag = 10000;
            [self.tableView addSubview:_nonePage];
        }
        //*/
    } showProgress:YES];
}

@end
